import mongoose from 'mongoose';

const MONGODB_URI = "mongodb://reader_db:123Aa@118.31.223.52:27017/reader_db?authSource=reader_db";
/* eslint-disable prefer-const */
let cached = (global as any).mongoose || { conn: null, promise: null };
/* eslint-enable prefer-const */
const connectToDatabase = async (): Promise<void> => {
    if (cached.conn) {
        console.log('✅ 使用已有的 MongoDB 连接');
        return;
    }

    if (!cached.promise) {
        cached.promise = mongoose.connect(MONGODB_URI, {
            useNewUrlParser: true,
            useUnifiedTopology: true,
        } as mongoose.ConnectOptions);
    }

    try {
    cached.conn = await cached.promise;
    console.log('✅ MongoDB 连接成功');
    } catch (error) {
        console.error('❌ MongoDB 连接失败:', error);
        // process.exit(1);
    }
};

(global as any).mongoose = cached;

export default connectToDatabase;
